<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机名称" prop="hostName">
        <el-input
          v-model="queryParams.hostName"
          placeholder="请输入主机名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机Ip" prop="hostIp">
        <el-input
          v-model="queryParams.hostIp"
          placeholder="请输入主机IP"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户密码" prop="userPass">
        <el-input
          v-model="queryParams.userPass"
          placeholder="请输入用户密码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:account:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:account:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:account:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:account:add']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:account:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleAllModify"
          v-hasPermi="['system:account:add']"
        >
          执行选中任务
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="名称" align="center" prop="hostName" />
      <el-table-column label="用户ID" align="center" prop="userId"/>
      <el-table-column label="主机IP" align="center" prop="hostIp"/>
      <el-table-column label="主机Port" align="center" prop="hostPort"/>
      <el-table-column label="用户名" align="center" prop="userName"/>
      <el-table-column label="策略" align="center" prop="policyName"/>
      <el-table-column label="模板" align="center" prop="templatesName"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="变更结果" align="center" prop="exeStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.exeStatus == 0">待执行</span>
          <span v-else-if="scope.row.exeStatus == 1">改密成功</span>
          <span v-else-if="scope.row.exeStatus == 2">改密失败</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:account:edit']"
          >修改
          </el-button>
          <!--el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleAllModify(scope.row)"
            v-hasPermi="['system:account:remove']"
          >执行
          </el-button-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:account:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleLog(scope.row)"
            v-hasPermi="['system:account:edit']"
          >日志
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改帐号管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="名称" prop="hostName">
          <el-input v-model="form.hostName" placeholder="请输入主机名称" />
        </el-form-item>
        <el-form-item label="主机IP" prop="hostIp">
          <el-input v-model="form.hostIp" placeholder="请输入主机IP"/>
        </el-form-item>
        <el-form-item label="主机Port" prop="hostPort">
          <el-input v-model="form.hostPort" placeholder="请输入主机Port"/>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="userPass">
          <el-input type="password" v-model="form.userPass" v-if="passshow" placeholder="请输入密码"/>
          <el-input type="text" v-model="form.userPass" v-else placeholder="请输入密码"/>
          <el-button @click="pwd_show">
            <div v-if="passshow">
              显示
            </div>
            <div v-else>
              隐藏
            </div>
          </el-button>
        </el-form-item>
        <el-form-item label="策略ID" prop="policyId">
          <el-select clearable v-model="form.policyId" @change="dataScopeSelectChange">
            <el-option
              v-for="(item,index) of polictList"
              :key="index"
              :label="item.policyName"
              :value="item.policyId"
            >{{item.policyName}}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板" prop="policyId">
          <el-select clearable v-model="form.templatesId" @change="dataScopeSelectChangeTemplate">
            <el-option
              v-for="(item,index) of templatesList"
              :key="index"
              :label="item.templatesName"
              :value="item.templatesId"
            >{{item.templatesName}}
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="新密码" prop="newUserPass">
          <el-input type="text" v-model="form.newUserPass" placeholder="请输入新密码"/>
          <el-button @click="pwd_gen">
            随机生成
          </el-button>
          <el-button type="primary" @click="pwd_modify">
            修改服务器密码
          </el-button>
        </el-form-item>-->

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog :title="logs.title" :visible.sync="logs.open" width="600px" append-to-body>
      <!-- <el-card class="update-log">
         <div slot="header" class="clearfix">
           <span>日志</span>
         </div>
         <el-collapse accordion>

           <el-collapse-item title="v1.0.0 - 2022-01-10">
             <ol>
               <li>密码更换工具前后端分离系统正式发布</li>
             </ol>
           </el-collapse-item>
           <el-collapse-item title="v1.0.0 - 2022-01-10">
             <ol>
               <li>密码更换工具前后端分离系统正式发布</li>
             </ol>
           </el-collapse-item>
         </el-collapse>
       </el-card>-->
      <el-table v-loading="loading" :data="logsList">
        <el-table-column label="日志ID" align="center" prop="logId"/>
        <el-table-column label="归属主机" align="center" prop="hostIp"/>
        <el-table-column label="旧密码" align="center" prop="oldPass"/>
        <el-table-column label="当前密码" align="center" prop="pass"/>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logs.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addAccount,
    delAccount,
    getAccount,
    getLog,
    getNewPass,
    listAccount,
    modifyAllPass,
    updateAccount
  } from "@/api/system/account";
  import {listPolicy} from "@/api/system/policy";
  import {listTemplates} from "@/api/system/templates";
  import {getToken} from "@/utils/auth";
  import {changeAccountStatus} from "../../../api/system/account";

  export default {
    name: "Account",
    data() {
      return {
        passshow: true,
        selectPolicy: "",
        polictList: [],
        templatesList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 帐号管理表格数据
        accountList: [],
        logsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/account/importData"
        },
        logs: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: ""
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          hostId: null,
          userName: null,
          userPass: null,
          status: null,
        },
        // 表单参数
        form: {
          userId: null,
          taskName: null,
          hostName: null,
          hostPort: null,
          hostIp: null,
          userName: null,
          userPass: null,
          policyId: null,
          templatesId: null,
          newUserPass: null,
          status: "0",
          exeStatus: "0",
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        },
        // 表单校验
        rules: {
          hostId: [
            {required: true, message: "归属主机不能为空", trigger: "blur"}
          ],
          userName: [
            {required: true, message: "用户名不能为空", trigger: "blur"}
          ],
          userPass: [
            {required: true, message: "用户密码不能为空", trigger: "blur"}
          ],
        }

      };
    },
    created() {
      this.getPoliceList();
      this.getTemplatesList();
      this.getList();
    },
    methods: {
      dataScopeSelectChange(policyId) {     //change 触发事件
        console.log(policyId);
        //绑定
      },
      dataScopeSelectChangeTemplate(templatesId) {     //change 触发事件
        console.log(templatesId);
        //绑定
      },
      /** 查询策略管理列表 */
      getPoliceList() {
        this.loading = true;
        listPolicy(this.queryParams).then(response => {
          console.log(response.rows);
          this.polictList = response.rows;
          /*this.total = response.total;
          this.loading = false;*/
        });
      },

      /** 查询模板列表 */
      getTemplatesList() {
        this.loading = true;
        listTemplates(this.queryParams).then(response => {
          console.log(response.rows);
          this.templatesList = response.rows;
          /*this.total = response.total;
          this.loading = false;*/
        });
      },
      /** 查询日志列表 */
      getlogsList(hostip) {
        getLog(hostip).then(response => {
          this.logsList = response.rows;
        });
      },
      /** 查询帐号管理列表 */
      getList() {
        this.loading = true;
        listAccount(this.queryParams).then(response => {
          this.accountList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.userId + '"用户吗？').then(function() {
          return changeAccountStatus(row.userId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      fileCancel() {
        this.fileopen = false;
      },
      // 表单重置
      reset() {
        this.form = {
          userId: null,
          taskName: null,
          hostName: null,
          hostPort: null,
          hostIp: null,
          userName: null,
          userPass: null,
          policyId: null,
          templatesId: null,
          status: "0",
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加帐号管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const userId = row.userId || this.ids
        getAccount(userId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改帐号管理";
        });
      },
      /** 修改按钮操作 */
      handleLog(row) {
        this.reset();
        const hostIp = row.hostIp;
        this.logs.open = true;
        this.logs.title = "日志查看-" + hostIp;
        this.getlogsList(hostIp).then(response => {
          this.open = true;
          this.title = "修改帐号管理";
        });
      },
      pwd_modify: function () {
        this.$modal.msgSuccess("修改成功");
      },
      pwd_gen: function () {
        const userId = row.userId || this.ids
        getNewPass(user).then(response => {
          this.form.newUserPass = response.data;

        });
        var m = "", i = 16;
        for (; i >= 0; i--) {
          m += String.fromCharCode(Math.floor(Math.random() * 94 + 33));
        }
        console.log("----------" + m);
        console.log("----------" + JSON.stringify(this.form));
        this.form.newUserPass = m;
      },
      handleAllModify(row) {
        const userIds = row.userId || this.ids;
        this.$modal.confirm('是否确认修改帐号管理编号为"' + userIds + '"的数据项？').then(function () {
          return modifyAllPass(userIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("修改成功");
        }).catch(() => {
        });

        /* modifyAllPass().then(response => {
           console.log(response);
         });*/
      },
      pwd_show: function () {
        this.passshow = !this.passshow
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.userId != null) {
              updateAccount(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addAccount(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.userId || this.ids;
        this.$modal.confirm('是否确认删除帐号管理编号为"' + userIds + '"的数据项？').then(function () {
          return delAccount(userIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      handleChangPwd(row) {
        const userIds = row.userId || this.ids;
        this.$modal.confirm('是否确认重置帐号管理编号为"' + userIds + '"的数据项？').then(function () {
          return changePwdAccount(userIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/account/export', {
          ...this.queryParams
        }, `account_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "帐号导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('system/account/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }

    }
  };
</script>
